package com.zhang.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 实现明天理想的唯一障碍是今天的疑虑
 *
 * @Author {张旭军}
 * @Date: 2023/02/05/ 23:04
 * @description  全局异常类处理
 */

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandle {

    /**
     * 拦截数据重复数据并提示前端
     */
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public R<String> controllerExceptionHandle(SQLIntegrityConstraintViolationException violationException){

        if(StringUtils.isNotBlank(violationException.getMessage()) && violationException.getMessage().contains("Duplicate entry")){
            String[] exceptionSplit = violationException.getMessage().split(" ");

            return R.error(exceptionSplit[2]+"已存在");
        }
        log.error("请求报错了：{}",violationException.getMessage());
        return R.error("未知异常,请联系开发人员排查");

    }
}
